package com.ly.hotel.spainterface.jxd.dialog;

import android.app.Dialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.MyLogsManager;
import com.ly.hotel.msgevent.SendLogEvent;
import com.ly.hotel.spainterface.jxd.activity.JxdXiaoFeiActivity;
import com.ly.hotel.spainterface.jxd.adapter.JxdXFActionAdapter;
import com.ly.hotel.spainterface.jxd.adapter.JxdXFUnitAdapter;
import com.ly.hotel.spainterface.jxd.bean.JxdXFActionBean;
import com.ly.hotel.spainterface.jxd.bean.JxdXFItemBean;
import com.ly.hotel.spainterface.jxd.bean.JxdXFUnitBean;
import com.ly.hotel.spainterface.jxd.event.JxdUnitEvent;
import com.ly.hotel.spainterface.nm.bean.NmXFBuyItemBean;
import com.ly.hotel.spainterface.nm.event.XFActionEvent;
import com.ly.hotel.spainterface.nm.event.XFBuyResEvent;
import com.ly.hotel.spainterface.nm.event.XFUpdateCartEvent;
import com.ly.hotel.util.ImageUtil;
import com.ly.hotel.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;


/**
 * Created by SHUBEN on 2018/3/22.
 */

public class JxdXFItemDetailsDialog extends Dialog {
    private MyApplication app;
    private JxdXiaoFeiActivity mcontext;
    private JxdXFItemBean itembean;
    private ImageView detailImg;
    private TextView itemName;          // 名称
    private TextView itemPrice;         // 单价
    private TextView itemCount;         // 数量
    private ListView actionListView;
    private ListView unitListView;
    private ImageButton subBt;
    private ImageButton addBt;
    private Button backBtn;
    private Button buyBtn;
    private Button addCartBtn;
    private int rod;
    private List<JxdXFActionBean> actionList;
    private List<JxdXFUnitBean> unitList;
    private NmXFBuyItemBean buyBean ;
    private JxdXFActionAdapter actionAdapter;
    private JxdXFUnitAdapter unitAdapter;
    private final int BUY_NOW = 1;
    private final int ADD_CART = 2;

    public JxdXFItemDetailsDialog(JxdXiaoFeiActivity context, int theme) {
        super(context, theme);
        mcontext = context;
        app = (MyApplication) mcontext.getApplicationContext();
        rod = mcontext.getResources().getDimensionPixelSize(R.dimen.px6);
    }

    public void initData(JxdXFItemBean b){
        EventBus.getDefault().register(this);
        itembean = b;
        actionList =  itembean.getAction();
        unitList = itembean.getUnitBeen();
        initBuyBean();
        initShowData();
    }

    //初始化下单数据类
    private void initBuyBean(){
        buyBean = new NmXFBuyItemBean();
        buyBean.setId(itembean.getNo());
        buyBean.setName(itembean.getName());
        buyBean.setUnit(itembean.getUnit());
        buyBean.setNum(1);
        buyBean.setPrice(Double.parseDouble(itembean.getPrice()));
        buyBean.setAction("");
        buyBean.setActionNo("");
    }

    private void initShowData(){
        itemCount.setText("1");
        itemName.setText(itembean.getName());
        itemPrice.setText(itembean.getPrice() + " " + mcontext.getResources().getString(R.string.xf_rmb)
                + " / " + itembean.getUnit());
        // 根据imgSrc配置是否使用收银系统的技师图片
        String imgPath = "";
        if (!TextUtils.isEmpty(mcontext.getImgSrc())){
            imgPath = mcontext.getImgSrc() + itembean.getNo() + ".jpg";
        }else {
            imgPath = MyApplication.getHostResUrl() + "/upload/interface/consume/pic/"
                    + itembean.getNo() + ".jpg";
        }
        ImageUtil.displayImage_Round(mcontext, imgPath, detailImg, rod);

        actionAdapter = new JxdXFActionAdapter(mcontext, actionList);
        actionListView.setAdapter(actionAdapter);

        unitAdapter = new JxdXFUnitAdapter(mcontext, unitList);
        unitListView.setAdapter(unitAdapter);
        unitListView.post(new Runnable() {
            @Override
            public void run() {
                buyBtn.requestFocus();
                buyBtn.requestFocusFromTouch();
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.jxd_xf_details);
        detailImg = findViewById(R.id.xf_detial_img);
        itemName = findViewById(R.id.xf_details_name);
        itemPrice = findViewById(R.id.xf_detials_price);
        itemCount = findViewById(R.id.xf_item_count);
        actionListView = findViewById(R.id.jxd_action_List);
        unitListView = findViewById(R.id.jxd_unit_List);

        TextView imgText = (TextView) findViewById(R.id.xf_details_remark);
        if(!TextUtils.isEmpty(mcontext.getPicRemark())){
            imgText.setText(mcontext.getPicRemark());
            imgText.setVisibility(View.VISIBLE);
        }else{
            imgText.setVisibility(View.GONE);
        }
        subBt = findViewById(R.id.xf_btn_sub);
        addBt = findViewById(R.id.xf_btn_add);
        backBtn = findViewById(R.id.dialog_back);
        buyBtn = findViewById(R.id.xf_buyNow);
        addCartBtn = findViewById(R.id.xf_btn_addCart);

        backBtn.setOnClickListener(btOnclick);
        subBt.setOnClickListener(btOnclick);
        addBt.setOnClickListener(btOnclick);
        buyBtn.setOnClickListener(btOnclick);
        addCartBtn.setOnClickListener(btOnclick);
        actionListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                actionAdapter.setSelectPosition(position);
                actionAdapter.notifyDataSetChanged();
            }
        });
        unitListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                unitAdapter.setSelectPosition(position);
                unitAdapter.notifyDataSetChanged();
            }
        });
    }

    private View.OnClickListener btOnclick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.xf_btn_sub:
                    int countSub = Integer.parseInt(itemCount.getText().toString());
                    if(countSub > 1){
                        itemCount.setText(countSub - 1 + "");
                        buyBean.setNum(countSub - 1);
                    }
                    break;
                case R.id.xf_btn_add:
                    int count = Integer.parseInt(itemCount.getText().toString());
                    if(count < mcontext.getMaxBuyCount()){
                        itemCount.setText(count + 1 + "");
                        buyBean.setNum(count + 1);
                    }else{
                        ToastUtil.showShortToast(mcontext, mcontext.getResources().getString(R.string.xf_nomorethan)
                                + " " + mcontext.getMaxBuyCount() + " " + mcontext.getItemTypeName(), 2000);
                    }
                    break;
                case R.id.dialog_back:
                    dismiss();
                    break;
                case R.id.xf_buyNow:
                    operationItem(BUY_NOW);
                    EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_XIAOFEI + "\t" +
                            MyApplication.interfaceVersion + "\t" + "下单"));
                    break;
                case R.id.xf_btn_addCart:
                    operationItem(ADD_CART);
                    EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_XIAOFEI + "\t" +
                            MyApplication.interfaceVersion + "\t" + "加入购物车"));
                    break;
            }
        }
    };

    //立即下单或加入购物车
    private void operationItem(int type){
        List<NmXFBuyItemBean> byList = new ArrayList<>();
        switch (type){
            case BUY_NOW:
                byList.add(buyBean);
                JxdXFBuyDialog buydialog = new JxdXFBuyDialog(mcontext,R.style.introDialog,byList);
                buydialog.setCanceledOnTouchOutside(false);//设置点击Dialog外部任意区域关闭Dialog
                buydialog.show();
                break;
            case ADD_CART:
                if((mcontext.getCartCount() + buyBean.getNum()) <= mcontext.getMaxBuyCount()) {
                    List<NmXFBuyItemBean> mycartList = app.shopCartList;
                    boolean isInCart = false;
                    for (NmXFBuyItemBean mi : mycartList) {
                        //编码、做法、单位相同才是同一商品
                        if (mi.getId().equals(buyBean.getId()) && mi.getActionNo().equals(buyBean.getActionNo())
                                && mi.getUnit().equals(buyBean.getUnit())) {
                            mi.setNum(mi.getNum() + buyBean.getNum());
                            isInCart = true;
                        }
                    }
                    if (!isInCart) {
                        app.shopCartList.add(buyBean);
                    }
                    EventBus.getDefault().post(new XFUpdateCartEvent(true,true));
                    dismiss();
                }else{
                    ToastUtil.showShortToast(mcontext, mcontext.getResources().getString(R.string.xf_nomorethan)
                            + " " + mcontext.getMaxBuyCount() + " " + mcontext.getItemTypeName(), 2000);
                }
                break;
        }
    }

    @Override
    protected void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }


    //选择做法时收到的信息
    public void onEventMainThread(XFActionEvent e){
        String key = e.getType();
        if (TextUtils.isEmpty(e.getName())){
            buyBean.setAction("");
            buyBean.setActionNo("");
        }else{
            buyBean.setAction(e.getName());
            buyBean.setActionNo(e.getType());
        }
    }

    //选择规格时收到的信息
    public void onEventMainThread(JxdUnitEvent e){
        String price = e.getuPrice();
        String unit = e.getuName();
        itemPrice.setText(price + " " + mcontext.getResources().getString(R.string.xf_rmb) + " / " + unit);
        buyBean.setPrice(Double.parseDouble(price));
        buyBean.setUnit(unit);
    }

    //收到下单返回,成功关闭窗口
    public void onEventMainThread(XFBuyResEvent e) {
        if (e.getTag()){
            dismiss();
        }
    }
}